package com.xmmxjy.dw.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xmmxjy.common.controller.BaseEndController;
import com.xmmxjy.common.util.*;
import com.xmmxjy.dw.entity.ArticleEntity;
import com.xmmxjy.dw.service.ArticleService;
import com.xmmxjy.dw.util.InterfaceTest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
*
* @author xmm
* @version :1.0
*/
@Controller
@RequestMapping(value="/article")
public class ArticleController extends BaseEndController {

private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);

private static final String CURRENT_PAGE = "article/";

@Autowired
private ArticleService articleService;


/**
* 列表页面
* @return
*/
@RequiresPermissions("dw.article.list")
@RequestMapping(value = "/list.do",method = {RequestMethod.GET,RequestMethod.POST})
public String list(@ModelAttribute ArticleEntity query, HttpServletRequest request, HttpServletResponse response,
@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize,ModelMap model) throws Exception{
//用了分页组件
    PageHelper.startPage(pageNo, pageSize);
    ArticleEntity article = new ArticleEntity();
    /**
    * 页面会转成空字符串，这里转成null，待后续想其他办法，这里加上转换，性能肯定有影响了
    */
    BeanUtil.copyBean2Bean(article,query);
List<ArticleEntity> list = articleService.select(article);
    logger.info("list : {}",list);
    model.addAttribute("query",query);
    PageInfo page = new PageInfo(list);
    //传入分页所需的参数
    EndUtil.sendPageParams(request,model,page);
    //传入固定的参数
    EndUtil.sendEndParams(request,model);
    return END_PAGE + CURRENT_PAGE + LIST;
    }

    /**
    * 新增页面
    * @param request
    * @param response
    * @param model
    * @return
    */
    @RequiresPermissions("dw.article.add")
    @RequestMapping(value = "/toAdd.do",method ={RequestMethod.GET, RequestMethod.POST})
    public String toAdd(HttpServletRequest request,HttpServletResponse response,ModelMap model){
        EndUtil.sendEndParams(request,model);
        return END_PAGE + CURRENT_PAGE + ADD;
    }

    /**
    * 修改页面
    * @param request
    * @param response
    * @param model
    * @return
    */
    @RequiresPermissions("dw.article.edit")
    @RequestMapping(value = "/toEdit.do",method ={RequestMethod.GET, RequestMethod.POST})
    public String toEdit(@RequestParam(required = true, value = "id" ) String id,HttpServletRequest request,HttpServletResponse response,ModelMap model){
    EndUtil.sendEndParams(request,model);
    ArticleEntity article = articleService.selectByPrimaryKey(id);
    System.out.println("..........." + ContextHolderUtils.replaceBlank(article.getContent()));
    model.addAttribute("article",article);
        return END_PAGE + CURRENT_PAGE + EDIT;
    }

    /**
    * 详情页面
    * @param request
    * @param response
    * @param model
    * @return
    */
    @RequiresPermissions("dw.article.detail")
    @RequestMapping(value = "/toDetail.do",method ={RequestMethod.GET, RequestMethod.POST})
    public String toDetail(@RequestParam(required = true, value = "id" ) String id,HttpServletRequest request,HttpServletResponse response,ModelMap model){
        EndUtil.sendEndParams(request,model);
        ArticleEntity article = articleService.selectByPrimaryKey(id);
        model.addAttribute("article",article);
        return END_PAGE + CURRENT_PAGE + DETAIL;
    }




    /**
    * 保存方法
    * @param article
    * @return
    */
    @RequiresPermissions("dw.article.add")
    @RequestMapping(value = "/doAdd.do",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doAdd(@ModelAttribute("article") ArticleEntity article){
        AjaxJson j = new AjaxJson();
        try {
            articleService.save(article);
            j.setMsg("保存成功");
        } catch (Exception e) {
            logger.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }

    /**
    * 更新方法
    * @param article
    * @return
    */
    @RequiresPermissions("dw.article.edit")
    @RequestMapping(value = "/doEdit.do",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute("article") ArticleEntity article){
    AjaxJson j = new AjaxJson();
        try {
        int i = articleService.updateByPrimaryKey(article);
        logger.info("i : ---- {}",i);
            if (i > 0) {
                j.setMsg("更新成功");
            } else {
                j.setMsg("更新失败");
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("更新失败");
        }
        return j;
    }

    @RequiresPermissions("dw.article.delete")
    @RequestMapping(value = "/doDelete.do",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doDelete(@RequestParam(required = true, value = "id")String id){
    AjaxJson j = new AjaxJson();
    try {
        int i= articleService.delete(id);
        if (i > 0) {
            j.setMsg("删除成功");
        } else {
            j.setMsg("删除失败");
        }
    } catch (Exception e) {
        logger.info(e.getMessage());
        j.setSuccess(false);
        j.setMsg("删除失败");
    }
        return j;
    }

    @RequestMapping(value = "/listAll.do")
    public List<ArticleEntity> tree() {
        logger.info("请求树形");
        List<ArticleEntity> channelList = articleService.selectAll();
        for (ArticleEntity articleEntity : channelList){
            articleEntity.setContent(ContextHolderUtils.replaceBlank(ContextHolderUtils.clearHtmlTag(articleEntity.getContent())));
            articleService.updateByPrimaryKey(articleEntity);
        }
        return channelList;
    }

    /**
     * 调用用户动作行为接口
     */
    /*@RequestMapping(value = "/userAction.do")
    public void userAction(){
        String url = "http://hadoop3:8990/syncAction.cp";
        Map<String,String> params = new HashMap<String,String>();
        params.put("version","1.0");
        params.put("uuid",Tools.getUUID());
        params.put("time",DateUtil.getCurrentTime());
        params.put("msisdn","");
        params.put("imsi","");
        params.put("imei","");
        params.put("client_device_number","");
        params.put("client_version","");
        params.put("os","");
        params.put("city","");
        params.put("id","");
        params.put("action","");
        params.put("referer","");
        params.put("ua","");
        params.put("reason","");

        String xml = HttpClientUtil.getInstance().sendHttpPost(url,params);
    }*/


    @RequestMapping(value = "userAction.do", method = RequestMethod.GET )
    public String toUserAction(HttpServletRequest request, HttpServletResponse response,ModelMap model) {

        EndUtil.sendEndParams(request,model);
        return END_PAGE + CURRENT_PAGE + "userAction";
    }
    @RequestMapping(value = "userAction.do", method = RequestMethod.POST )
    @ResponseBody
    public Object doUserAction(String url,String id, String msisdn, String imsi, String imei, String clientDeviceNumber, String action, String referer, String reason) {
        return InterfaceTest.userAction(url,id,msisdn,imsi,imei,clientDeviceNumber,action,referer,reason);
    }

    @RequestMapping(value = "userPreference.do", method = RequestMethod.GET )
    public String toUserPreference(HttpServletRequest request, HttpServletResponse response,ModelMap model) {

        EndUtil.sendEndParams(request,model);
        return END_PAGE + CURRENT_PAGE + "userPreference";
    }
    @RequestMapping(value = "userPreference.do", method = RequestMethod.POST )
    @ResponseBody
    public Object doUserPreference(String url,String id, String msisdn, String imsi, String imei, String clientDeviceNumber, String channels) {
        return InterfaceTest.userPreference(url,msisdn,imsi,imei,clientDeviceNumber,channels);
    }

    /**
     * 通过数据库调用新闻同步接口
     */

    /**
     *调用用户编好接口
     */
    @RequestMapping(value = "/newSync.do")
    public void newSyncByDataBase(String url,Integer start,Integer count) {
        ArticleEntity article = new ArticleEntity();
        PageHelper.startPage(start, 100);
        List<ArticleEntity> articleList = articleService.selectAll();

        if (articleList != null && articleList.size() > 0) {
            for (ArticleEntity articleEntity :articleList) {
                if (articleEntity != null) {
                    String content = articleEntity.getContent();
                    if (content != null && !content.trim().equals("") && articleEntity.getIsPublication()) {
                        InterfaceTest.newsSync(url,"insert", articleEntity.getId(),
                                articleEntity.getTitle(),"",articleEntity.getArticleCategoryId(),
                                articleEntity.getKeyword(),articleEntity.getContent(),articleEntity.getUrl(),
                                DateUtil.dateToString(new Date()),
                                null,"0");
                    }
                }
            }
        }
    }

}
